const uploadFile = (files, options) => {
   const {
      onSuccess = undefined,
      onUploadStart = undefined,
      onUploadProgress = undefined,
      onUploadSuccess = undefined,
      onUploadEnd = undefined,
      onTimeout = undefined,
      onError = undefined,
      onAbort = undefined,
      abortHandler = undefined,
      index = '1',
   } = options;

   return new Promise((resolve, reject) => {
      const xhr = new XMLHttpRequest();
      xhr.timeout = 60 * 1000;
      xhr.open('POST', '/upload', true);
      xhr.onerror = (ev) => {
         console.log('请求错误', ev);
         reject(index)
      };
      xhr.ontimeout = (ev) => {
         console.log('请求超时');
         onTimeout && onTimeout();
         reject(index)
      };

      // 监听终止上传事件
      const handleAbort = () => {
         if (xhr.readyState !== XMLHttpRequest.DONE) {
            xhr.abort();
            onAbort && onAbort();
         }
      };
      abortHandler && abortHandler.addEventListener('click', handleAbort);

      // 上传到服务器的过程
      xhr.upload.addEventListener('abort', () => {
         console.log('上传中止');
      });
      xhr.upload.addEventListener('error', () => {
         console.log('上传失败');
         onError && onError('上传过程中出现错误');
      });
      xhr.upload.addEventListener('loadstart', (event) => {
         console.log('开始上传');
         onUploadStart && onUploadStart();
      });
      xhr.upload.addEventListener('load', (event) => {
         console.log('上传成功');
         onUploadSuccess && onUploadSuccess();
      });
      xhr.upload.addEventListener('loadend', (event) => {
         console.log('彻底结束: 终止、失败、成功都会调用这个');
         onUploadEnd && onUploadEnd();
         abortHandler && abortHandler.removeEventListener('click', handleAbort);
      });
      xhr.upload.addEventListener('progress', (event) => {
         const percentage = (event.loaded / event.total) * 100;
         onUploadProgress && onUploadProgress(`${percentage.toFixed(2)}%`);
      });

      // 服务器响应的过程（服务器接收到文件后保存&校验等也是一个过程）
      xhr.onreadystatechange = (ev) => {
         if (xhr.readyState === 4) {
            if (xhr.status !== 200) {
               onError && onError(xhr.responseText);
               reject(index)
            } else {
               console.log('上传成功');
               onSuccess && onSuccess();
               resolve(index)
            }
         }
      };

      // 创建formdata
      const formData = new FormData();
      if (Array.isArray(files)) {
         files.forEach((file) => {
            formData.append('image', file);
         });
      } else {
         formData.append('image', files);
      }

      xhr.send(formData);
   });
};
